package com.jckl.foodathon.restlet.services;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import com.google.gson.Gson;
import com.jckl.foodathon.common.constant.ApplicationConstants;
import com.jckl.foodathon.dao.LocationServiceDAO;
import com.jckl.foodathon.model.Coordinate;
import com.jckl.foodathon.model.Store;


/**
 * Resource which has only one representation.
 * 
 */
public class StoreLocationResource extends ServerResource {
	
	private static final Logger log = Logger.getLogger(StoreLocationResource.class.getName());

    @Put("json")
    public String getNearbyStore(Representation entity) {
    	
    	String returnString = "";
    	try{
    		JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
    		Gson gson = new Gson();
    		
    		Coordinate coordinate = gson.fromJson(req.toString(), Coordinate.class);
    		
    		int pageSize = ApplicationConstants.STORE_PAGE_SIZE;
    		int resultSize = 10;
    		int queryCount = coordinate.getQueryCount();
    		
    		if(queryCount > 1){
    			resultSize = resultSize * queryCount;
    		}
    		
    		LocationServiceDAO locService = new LocationServiceDAO();
    		List<Store> stores = locService.getNearbyStores(coordinate, resultSize, 0);
    		
    		for(int i=0;i<(resultSize - pageSize);i++){
    			stores.remove(i);
    		}
    		
    		returnString = new Gson().toJson(stores);

    	}catch(JSONException jsonEx){
    		jsonEx.printStackTrace();
    	}catch(IOException ioEx){
    		ioEx.printStackTrace();
    	}
		return returnString;
    }
    
    @Get
    public String testNearbyStore(){
    	String returnString = "";
		Coordinate coordinate = new Coordinate(3.203798, 101.675179, "");
		
		LocationServiceDAO locService = new LocationServiceDAO();
		List<Store> stores = locService.getNearbyStores(coordinate, 50, 0);
		
		returnString = new Gson().toJson(stores);
		return returnString;
    }
    
}
